package cn.yunhe;

import net.sf.json.JSONObject;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * Created by zs on 2017/10/31.
 */

@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/htm; charset=UTF-8");
        //设置响应头允许ajax跨域 ,星号表示所有的异域请求都可以接受
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "GET,POST");

        PrintWriter out = response.getWriter();
        JSONObject json = JsonReader.receivePost(request);
        System.out.println(json);

        UserBiz userBiz = new UserBiz();
        //将解析到的json数据转换为对象
        User loginUser = (User) JSONObject.toBean(json, User.class);
        User user = userBiz.loginUser(loginUser);
        JSONObject jsonObject = new JSONObject();

        if (user != null) {
            jsonObject.put("user", JSONObject.fromObject(user));
            jsonObject.put("message", "登录成功");
        } else {
            jsonObject.put("message", "登录失败");
        }


        out.write(jsonObject.toString());
        out.flush();
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }


}
